package com.chen.pfm.utils;

import com.chen.pfm.entity.Classify;
import com.chen.pfm.entity.DisplayBill;
import com.chen.pfm.entity.OrmPfmStore;
import com.chen.pfm.entity.ResultVo;
import com.google.gson.Gson;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.app.Context;
import ohos.app.dispatcher.TaskDispatcher;
import ohos.app.dispatcher.task.TaskPriority;
import ohos.data.DatabaseHelper;
import ohos.data.dataability.DataAbilityPredicates;
import ohos.data.orm.OrmContext;
import ohos.data.resultset.ResultSet;
import ohos.global.resource.NotExistException;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.Size;
import ohos.utils.net.Uri;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MyUtil {
    static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0x2022003, "MyUtil");
    //ngrok工具的通道的地址
    public static String ngrokUri = "http://huan.gz2vip.91tunnel.com";
    public static String updateUser = ngrokUri + "/user/updateUserInfoByUid";
    public static String updatePasswordByUid = ngrokUri + "/user/updatePasswordByUid";
    public static String updateGradeByUid = ngrokUri + "/user/updateGradeByUid";
    public static String createAccount = ngrokUri + "/account/createAccount";
    public static String createClassify = ngrokUri + "/classify/createClassify";
    public static String deleteClassifyByCid = ngrokUri + "/classify/deleteClassifyByCid";
    public static String updateBudgetByUid = ngrokUri + "/statement/updateBudgetByUid";
    public static String findAllStatementByUid = ngrokUri + "/statement/findAllStatementByUid?uid=";
    public static String login = ngrokUri + "/user/login";
    public static String findAllClassifyByUid = MyUtil.ngrokUri + "/classify/findAllClassifyByUid?uid=";
    public static String findAllAccountByUid = MyUtil.ngrokUri + "/account/findAllAccountByUid?uid=";


    //将金额转化为保留小数点两位的数
    public static String getStrBalance(double balance) {
        return String.format("%.2f", balance);
    }


    //判断字符串是否符合金额规范
    public static boolean isMoneyNumber(String balance) {
        // 整数
        // 包含负数
        if (balance == null) return false;
        Pattern pattern;
        if (balance.contains(".")) {//如果是小数
            pattern = Pattern.compile("^-?(([1-9]{1}[0-9]{1,11})|([0]{1}))(.[0-9]{1,2})?$");
        } else {
            //由于double是15-16位的精度，整数部分应该是12位
            pattern = Pattern.compile("^-?([1-9]{1}[0-9]{1,11})$");
        }
        //如果是整数就匹配13位，如果是小数就匹配10位整数和2位小数，还有1位小数点
        //$是匹配结束符

        Matcher match = pattern.matcher(balance);
        return match.matches();
    }

    public static Double getDoubleBalancefromStr(String balance) {

        return Double.valueOf(balance);
    }

    public static String randomUUID() {
        UUID uuid = UUID.randomUUID();
        return uuid.toString().replace("-", "").toUpperCase();
    }

    public static double getTotalAmoney(List<DisplayBill> displayBills, int ctype1) {

        double Total = 0.0;
        if (displayBills == null) {
            return 0.0;
        }
        for (int i = 0; i < displayBills.size(); i++) {
            if (displayBills.get(i).getType1() == ctype1) {
                Total += displayBills.get(i).getAmoney();
            }

        }
        return Total;
    }

    public static List<DisplayBill> queryDisplayBillByCondition(Context context, String Artime, String Aid) throws DataAbilityRemoteException {
        DisplayBill displayBill = null;
        List<DisplayBill> list = new ArrayList<>();
        DataAbilityHelper helper = DataAbilityHelper.creator(context);
        // 构造第一部分查询条件
        DataAbilityPredicates predicates = new DataAbilityPredicates();
        if (Artime != null) {
            predicates.beginsWith("artime", Artime);
        } else if (Aid != null) {
            predicates.equalTo("aid", Aid);
        } else {
            //不做操作
        }

        String[] columns1 = new String[]{"aid", "cid", "amoney", "aremark", "artime", "actime"};
        Uri uri = Uri.parse("dataability:///com.chen.pfm.AccountDataAbility/account");
        ResultSet resultSet = helper.query(uri, columns1, predicates);


        if (resultSet == null) return null;
        if (resultSet.getRowCount() > 0) {
            // 处理结果
            resultSet.goToFirstRow();
            do {

                String aid = resultSet.getString(0);
                String cid = resultSet.getString(1);
                Classify classify = ClassifyDBUtil.queryOneClassifyByCid(context, cid);
                if (classify.getCtype_1() != 3) {
                    Double amoney = resultSet.getDouble(2);
                    String aremark = resultSet.getString(3);
                    String artime = resultSet.getString(4);
                    String actime = resultSet.getString(5);
                    displayBill = new DisplayBill();
                    displayBill.setAid(aid);
                    displayBill.setCid(cid);
                    displayBill.setAmoney(amoney);
                    displayBill.setAremark(aremark);
                    displayBill.setRecordTime(artime);
                    displayBill.setCreatTime(actime);
                    if (classify != null) {
                        displayBill.setCid(classify.getCid());
                        displayBill.setIcon(classify.getImage());
                        displayBill.setCname(classify.getCname());
                        displayBill.setType1(classify.getCtype_1());
                    } else {
                        HiLog.error(LABEL, "当前账单aid为" + aid + "无对应的分类");
                    }
                    list.add(displayBill);
                }

            } while (resultSet.goToNextRow());

        } else {
            return null;
        }
        return list;
    }

    public static List<DisplayBill> queryDisplayTotalBill(Context context) throws DataAbilityRemoteException {
        return queryDisplayBillByCondition(context, null, null);
    }

    public static List<DisplayBill> queryDisplayTotalBillAndArtime(Context context, String Artime) throws DataAbilityRemoteException {
        return queryDisplayBillByCondition(context, Artime, null);
    }

    public static List<DisplayBill> queryDisplayBillByArtime(Context context, String Artime) throws DataAbilityRemoteException {
        return queryDisplayBillByCondition(context, Artime, null);
    }


    public static List<DisplayBill> searchDisplayBillByCondition(Context context, String searchWord, int i) throws DataAbilityRemoteException {
        DisplayBill displayBill = null;
        List<DisplayBill> list = new ArrayList<>();
        DataAbilityHelper helper = DataAbilityHelper.creator(context);
        // 构造第一部分查询条件
        DataAbilityPredicates predicates = new DataAbilityPredicates();
        if (i == 1) {
            predicates.equalTo("amoney", searchWord).or().beginsWith("amoney", searchWord);
        } else if (i == 3) {
            predicates.beginsWith("aremark", searchWord);
        } else if (i == 2) {

            predicates.beginsWith("artime", searchWord).or().equalTo("artime", searchWord);
        } else {
            predicates.beginsWith("amoney", String.valueOf(searchWord)).or().beginsWith("aremark", searchWord).or().beginsWith("artime", searchWord);
        }
        String[] columns = new String[]{"aid", "cid", "amoney", "aremark", "artime", "actime"};
        Uri uri = Uri.parse("dataability:///com.chen.pfm.AccountDataAbility/account");
        ResultSet resultSet = helper.query(uri, columns, predicates);


        if (resultSet == null) return null;
        if (resultSet.getRowCount() > 0) {
            // 处理结果
            resultSet.goToFirstRow();
            do {

                String aid = resultSet.getString(0);
                String cid = resultSet.getString(1);
                Classify classify = ClassifyDBUtil.queryOneClassifyByCid(context, cid);
//                if (classify.getCtype_1() != 3) {
                Double amoney = resultSet.getDouble(2);
                String aremark = resultSet.getString(3);
                String artime = resultSet.getString(4);
                String actime = resultSet.getString(5);
                displayBill = new DisplayBill();
                displayBill.setAid(aid);
                displayBill.setCid(cid);
                displayBill.setAmoney(amoney);
                displayBill.setAremark(aremark);
                displayBill.setRecordTime(artime);
                displayBill.setCreatTime(actime);
                if (classify != null) {
                    displayBill.setCid(classify.getCid());
                    displayBill.setIcon(classify.getImage());
                    displayBill.setCname(classify.getCname());
                    displayBill.setType1(classify.getCtype_1());
                } else {
                    HiLog.error(LABEL, "当前账单aid为" + aid + "无对应的分类");
                }
                list.add(displayBill);
//                }

            } while (resultSet.goToNextRow());

        } else {
            return null;
        }
        return list;
    }

    //展示详情页面
    public static DisplayBill queryDisplayBillByAid(Context context, String findaid) throws DataAbilityRemoteException {
        DisplayBill displayBill = null;
        DataAbilityHelper helper = DataAbilityHelper.creator(context);
        // 构造第一部分查询条件
        DataAbilityPredicates predicates = new DataAbilityPredicates();
        predicates.equalTo("aid", findaid);
        String[] columns = new String[]{"aid", "cid", "amoney", "aremark", "artime", "actime"};
        Uri uri = Uri.parse("dataability:///com.chen.pfm.AccountDataAbility/account");
        ResultSet resultSet = helper.query(uri, columns, predicates);
        if (resultSet.getRowCount() > 0) {
            // 处理结果
            resultSet.goToFirstRow();
            String aid = resultSet.getString(0);
            String cid = resultSet.getString(1);
            Classify classify = ClassifyDBUtil.queryOneClassifyByCid(context, cid);
            Double amoney = resultSet.getDouble(2);
            String aremark = resultSet.getString(3);
            String artime = resultSet.getString(4);
            String actime = resultSet.getString(5);
            displayBill = new DisplayBill();
            displayBill.setAid(aid);
            displayBill.setCid(cid);
            displayBill.setAmoney(amoney);
            displayBill.setAremark(aremark);
            displayBill.setRecordTime(artime);
            displayBill.setCreatTime(actime);
            if (classify != null) {
                displayBill.setCid(classify.getCid());
                displayBill.setIcon(classify.getImage());
                displayBill.setCname(classify.getCname());
                displayBill.setType1(classify.getCtype_1());
            } else {
                HiLog.error(LABEL, "当前账单aid为" + aid + "无对应的分类");
            }
        } else {
            return null;
        }
        return displayBill;
    }

    public static List<DisplayBill> queryDisplayAssetByCondition(Context context, String Artime, String Aid) throws DataAbilityRemoteException {
        DisplayBill displayBill = null;
        List<DisplayBill> list = new ArrayList<>();
        DataAbilityHelper helper = DataAbilityHelper.creator(context);
        // 构造第一部分查询条件
        DataAbilityPredicates predicates = new DataAbilityPredicates();
        if (Artime != null) {
            predicates.beginsWith("artime", Artime);
        } else if (Aid != null) {
            predicates.equalTo("aid", Aid);
        } else {
            //不做操作
        }
        String[] columns = new String[]{"aid", "cid", "amoney", "aremark", "artime", "actime"};
        Uri uri = Uri.parse("dataability:///com.chen.pfm.AccountDataAbility/account");
        ResultSet resultSet = helper.query(uri, columns, predicates);
        if (resultSet == null) return null;
        if (resultSet.getRowCount() > 0) {
            // 处理结果
            resultSet.goToFirstRow();
            do {

                String aid = resultSet.getString(0);
                String cid = resultSet.getString(1);
                Classify classify = ClassifyDBUtil.queryOneClassifyByCid(context, cid);
                if (classify.getCtype_1() == 3) {
                    Double amoney = resultSet.getDouble(2);
                    String aremark = resultSet.getString(3);
                    String artime = resultSet.getString(4);
                    String actime = resultSet.getString(5);
                    displayBill = new DisplayBill();
                    displayBill.setAid(aid);
                    displayBill.setCid(cid);
                    displayBill.setAmoney(amoney);
                    displayBill.setAremark(aremark);
                    displayBill.setRecordTime(artime);
                    displayBill.setCreatTime(actime);
                    if (classify != null) {
                        displayBill.setCid(classify.getCid());
                        displayBill.setIcon(classify.getImage());
                        displayBill.setCname(classify.getCname());
                        displayBill.setType1(classify.getCtype_1());
                    } else {
                        HiLog.error(LABEL, "当前账单aid为" + aid + "无对应的分类");
                    }
                    list.add(displayBill);
                }

            } while (resultSet.goToNextRow());

        } else {
            return null;
        }
        return list;
    }



    public static List<DisplayBill> queryDisplayTotalAsset(Context context) throws DataAbilityRemoteException {
        return queryDisplayAssetByCondition(context, null, null);
    }

    public static List<DisplayBill> queryDisplayBillByPastSevenDays(Context context) throws DataAbilityRemoteException {
        String[] pastSevenDate = DateUtils.getPastSevenDate();
        List<DisplayBill> displayBills = new ArrayList<>();
        for (int i = 0; i < 7; i++) {
            List<DisplayBill> displayBills1 = queryDisplayBillByArtime(context, pastSevenDate[i]);
            if (displayBills1 != null) {
                displayBills.addAll(displayBills1);
            }
        }
        return displayBills;
    }


}
